package com.share.device.emqx.handler.impl;

import com.alibaba.fastjson2.JSONObject;
import com.share.common.core.constant.DeviceConstants;
import com.share.device.domain.Cabinet;
import com.share.device.domain.PowerBank;
import com.share.device.emqx.annotation.GuiguEmqx;
import com.share.device.emqx.constant.EmqxConstants;
import com.share.device.emqx.handler.MassageHandler;
import com.share.device.service.ICabinetService;
import com.share.device.service.ICabinetSlotService;
import com.share.device.service.IPowerBankService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

@Slf4j
@Component
@GuiguEmqx(topic = EmqxConstants.TOPIC_PROPERTY_POST)
public class PropertyPostHandler implements MassageHandler {

    @Autowired
    private ICabinetService cabinetService;

    @Autowired
    private IPowerBankService powerBankService;

    @Autowired
    private ICabinetSlotService cabinetSlotService;

    @Autowired
    private RedisTemplate redisTemplate;


    /**
     * 处理消息:
     * @param message
     */
    @Override
    @Transactional
    public void handleMessage(JSONObject message) {
        log.info("开始处理属性上报消息: {}", message);
        
        try {
            // 检查消息是否为空
            if (message == null || message.isEmpty()) {
                log.warn("收到空消息");
                return;
            }

            // 从消息中获取充电宝编号和电量
            String powerBankNo = message.getString("pNo");
            String cabinetNo = message.getString("cNo");
            String slotNo = message.getString("sNo");
            BigDecimal electricity = message.getBigDecimal("ety");
            PowerBank powerBank = powerBankService.getByPowerBankNo(powerBankNo);
            powerBank.setElectricity(electricity);

            if (electricity.subtract(DeviceConstants.ELECTRICITY_MIN).doubleValue() > 0) {
                //可以借用
                powerBank.setStatus("1");
            } else {
                //充电中
                powerBank.setStatus("3");
            }

            boolean b = powerBankService.updateById(powerBank);

            if (b) {

                cabinetService.updateCabinetNo(cabinetNo);
                log.info("更新充电宝电量成功: powerBankNo={}, slotNo={}, electricity={}", 
                        powerBankNo, slotNo, electricity);
            } else {
                log.warn("更新充电宝电量失败: powerBankNo={}, slotNo={}, electricity={}", 
                        powerBankNo, slotNo, electricity);
            }
        } catch (Exception e) {
            log.error("处理充电宝电量更新消息失败: message={}", message, e);
        }
    }
}

